<template>
  <div class="tpl-container">
    <div class="mb20">
      <span class="color_494949 ft12 pr5">{{ translate('模板编码') }}：</span>
      <ElInput
        v-model="eslCode"
        class="w164 mr14"
        :placeholder="translate('请输入模板编码')"
      />
      <span class="color_494949 ft12 pr5">{{ translate('模板名称') }}：</span>
      <ElInput
        v-model="eslName"
        class="w164 mr14"
        :placeholder="translate('请输入模板名称')"
      />
      <span class="color_494949 ft12 pr5">
        {{ translate('模板适用类型') }}：
      </span>
      <el-select v-model="lcdType" class="mr14 w164" placeholder="select">
        <el-option
          v-for="item in types"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <ElButton class="settingBtn" type="primary" @click="search">
        {{ translate('查询') }}
      </ElButton>
    </div>
    <div class="add">
      <ElButton
        v-if="MenuAuth('add')"
        class="settingBtn"
        plain
        type="primary"
        @click="addFn"
      >
        {{ translate('新增') }}
      </ElButton>
    </div>
    <div class="table">
      <ElTable v-loading="loading" :border="true" :data="tableData">
        <ElTableColumn
          :label="translate('公司')"
          prop="CompanyName"
          width="auto"
        />
        <ElTableColumn :label="translate('模板编号')" prop="ID" width="auto" />
        <ElTableColumn :label="translate('模板编码')" width="130">
          <template #default="{ row }">
            <div>
              <span class="iconcolor">{{ row.CSTCode }}</span>
              <vab-icon icon="file-copy-line" @click="copyToClipboard(row.CSTCode)" />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          :label="translate('模板名称')"
          prop="CSTName"
          width="auto"
        />
        <ElTableColumn :label="translate('宽度')" prop="CSWidth" width="auto" />
        <ElTableColumn
          :label="translate('高度')"
          prop="CSHeight"
          width="auto"
        />
        <ElTableColumn :label="translate('模板图')">
          <template #default="{ row }">
            <div class="img-container">
              <ElImage
                fit="contain"
                :hide-on-click-modal="true"
                :initial-index="9"
                :preview-src-list="[row.Image]"
                :src="row.Image"
                :z-index="99999"
                :zoom-rate="1.2"
              />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('预览图')">
          <template #default="{ row }">
            <div v-if="row.PathImg" class="img-container">
              <ElImage
                fit="contain"
                :hide-on-click-modal="true"
                :initial-index="9"
                :preview-src-list="[row.PathImg]"
                :src="row.PathImg"
                :z-index="99999"
                :zoom-rate="1.2"
              />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          :label="translate('商品数量')"
          prop="ProNum"
          width="auto"
        />
        <ElTableColumn :label="translate('状态')">
          <template #default="{ row }">
            <div class="status">
              {{ row.Enabled == 1 ? translate('正常') : translate('未生效') }}
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('操作')" width="200">
          <template #default="{ row }">
            <ElButton
              v-if="MenuAuth('edit')"
              size="small"
              plain
              type="primary"
              @click="editFn(row)"
            >
              {{ translate('编辑') }}
            </ElButton>
            <ElButton
              v-if="MenuAuth('delete')"
              size="small"
              plain
              type="danger"
              @click="deleteFn(row)"
            >
              {{ translate('删除') }}
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
      <div v-if="total > 0" class="pagination">
        <ElPagination
          background
          :current-page="searchInfo.pageNo"
          :layout="layout"
          :page-size="searchInfo.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import { MenuAuth } from '~/src/utils/permission'
  import { getCsPageData, delCstemp } from '@/api/mupro'
  import router from '@/router'
  import { useEleStore } from '@/store/modules/coms'
  import { translate } from '@/i18n'
  const eslCode = ref('')
  const eslName = ref('')
  const lcdType = ref('')
  const types = ref([
    {
      value: '',
      label: translate('全部'),
    },
    {
      value: '00',
      label: '600*1024',
    },
    {
      value: '01',
      label: '600*664',
    },
    {
      value: '02',
      label: '600*620',
    },
    {
      value: '10',
      label: '1024*600',
    },
    {
      value: '11',
      label: '664*600',
    },
    {
      value: '12',
      label: '620*600',
    },
    {
      value: '03',
      label: '800*1280',
      data: {
        width: 800,
        height: 1280,
      },
    },
    {
      value: '04',
      label: '800*830',
      data: {
        width: 800,
        height: 830,
      },
    },
    {
      value: '05',
      label: '800*680',
      data: {
        width: 800,
        height: 680,
      },
    },
  ]) // 屏幕类型选项
  const searchInfo = reactive({
    pageNo: 1,
    pageSize: 20,
    tableName: '',
    sort: '',
    order: '',
    wheres: `[{"name":"CSTCode","value":${eslCode.value},"displayType":"like"}, {"name":"CSTName","value":${eslName.value},"displayType":"like"}, {"name":"LCDType","value":${lcdType.value},"displayType":"like"}]`,
    export: false,
    value: '',
  })
  const loading = ref(false)
  const { clearWidgets, clearEditorData } = useEleStore()
  const addFn = async () => {
    await clearWidgets()
    await clearEditorData()
    router.push({ path: '/mupro/csEditor' })
  }

  const layout = ref('total, sizes, prev, pager, next, jumper')
  const tableData = ref([])
  const total = ref(0)
  // 获取表格数据
  const gettableData = async () => {
    loading.value = true
    const { data } = await getCsPageData(searchInfo)
    loading.value = false
    tableData.value = data?.rows || []
    total.value = data?.total || 0
  }
  gettableData()
  //分页条数切换
  const handleSizeChange = (val: any) => {
    searchInfo.pageSize = val
    gettableData()
  }
  //分页切换
  const handleCurrentChange = (val: any) => {
    searchInfo.pageNo = val
    gettableData()
  }
   //复制彩屏标识
 const copyToClipboard =async (val: any) => {
    if (navigator.clipboard && window.isSecureContext) {
      try {
      console.log(navigator.clipboard)
      console.log(window.isSecureContext)
      await navigator.clipboard.writeText(val)
      ElMessage({
        message:'复制成功',
        type:'success',
      })
      } catch (err) {
        ElMessage({
        message:'复制失败',
        type:'error',
      })
      }

    }else {
      // 创建text area
    const textArea = document.createElement("textarea")
    textArea.value = val
    // 使text area不在viewport，同时设置不可见
    textArea.style.position = "absolute"
    textArea.style.opacity = 0
    textArea.style.left = "-999999px"
    textArea.style.top = "-999999px"
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()

    return new Promise((res, rej) => {
      // 执行复制命令并移除文本框
      document.execCommand("copy") ? res() : rej()
      textArea.remove()
    }).then(() => {
         ElMessage({
          message: "复制成功",
          type: "success",
        })
      }).catch((err) => {
        ElMessage({
          message: "复制失败",
          type: "error",
        })
      })
    }

  }

  const search = () => {
    searchInfo.pageNo = 1
    if (
      eslCode.value.trim() !== '' ||
      eslName.value.trim() !== '' ||
      lcdType.value.trim() !== ''
    ) {
      const arr = []
      eslCode.value.trim() !== '' &&
        arr.push({ name: 'CSTCode', value: eslCode.value, displayType: 'like' })
      eslName.value.trim() !== '' &&
        arr.push({ name: 'CSTName', value: eslName.value, displayType: 'like' })
      lcdType.value.trim() !== '' &&
        arr.push({ name: 'LCDType', value: lcdType.value, displayType: 'like' })
      searchInfo.wheres = JSON.stringify(arr)
    } else {
      searchInfo.wheres = `[{"name":"CSTCode","value": '',"displayType":"like"}, {"name":"CSTName","value": '',"displayType":"like"}, {"name":"LCDType","value": '',"displayType":"like"}]`
    }
    gettableData()
  }
  const editFn = (row: any) => {
    router.push({ path: `/mupro/csEditor`, query: { ID: row.ID } })
  }
  const $baseConfirm = inject('$baseConfirm') as any
  const deleteFn = async (row: any) => {
    $baseConfirm(translate('你确定要删除当前项吗'), null, async () => {
      await delCstemp({
        id: row.ID,
      })
      gettableData()
    })
  }
</script>

<style lang="scss" scoped>
  .tpl-container {
    .color_494949 {
      color: #494949;
    }
    .iconcolor {
      color: #409eff;
    }
    .status {
      color: #e6a23c;
    }
    .noData {
      text-align: center;
      font-size: 16px;
      color: gray;
    }
    .w164 {
      width: 164px;
    }
    .mb20 {
      margin-bottom: 20px;
    }
    .mr14 {
      margin-right: 14px;
    }

    .img-container {
      display: flex;
      // justify-content: center;

      .img {
        width: 100px;
      }
    }
    .add {
      margin-bottom: 10px;
      text-align: left;
    }
  }
  .el-table {
    & ::v-deep th.el-table__cell,
    ::v-deep td.el-table__cell {
      // 设置position 使得 子元素不与其产生新的层叠关系
      position: static;
    }
  }
</style>
